import { interfacesUser } from '../../interfaces/user';
import { setStorage, storageKey } from '../../utils/storage';
import { setToken } from '../../utils/token';
import { useNavigate } from 'react-router-dom';
import './index.scss'
import { WalletButton } from '../WalletButton';
import { UnifiedWalletProvider } from "@jup-ag/wallet-adapter";

function ConnectWallet({ size, onConnected }) {
  const navigate = useNavigate()

  /** 钱包消息回调 */
  const WalletNotification = {
    onConnect: (props) => {
      console.log(props);
      const { publicKey, shortAddress, metadata } = props;
      setStorage(storageKey.publicKey, publicKey);
      setStorage(storageKey.walletIcon, metadata.icon);
      setStorage(storageKey.walletShortAddress, shortAddress);
      login(publicKey);
      onConnected();
    },
    onConnecting: (props) => {
      console.log(props);
    },
    onDisconnect: (props) => {
      console.log(props);
    },
    onNotInstalled: (props) => {
      console.log(props);
    },
  }

  /** 登录 */
  const login = (publicKey) => {
    const params = {
      pubkey: publicKey
    }
    interfacesUser.login(params).then(res => {
      console.log(res);
      if (res.code === 0) {
        const { token } = res.data;
        setToken(token);
      } else if (res.code === 1002) {
        navigate('/register')
      }
    })
  }

  return (
    <UnifiedWalletProvider
      wallets={[]}
      config={{
        autoConnect: false,
        env: 'mainnet-beta',
        metadata: {
          name: 'UnifiedWallet',
          description: 'UnifiedWallet',
          url: 'https://jup.ag',
          iconUrls: ['https://jup.ag/favicon.ico'],
        },
        notificationCallback: WalletNotification,
        walletlistExplanation: {
          href: 'https://station.jup.ag/docs/additional-topics/wallet-list',
        },
      }}
    >
      <WalletButton size={size} />
    </UnifiedWalletProvider>
  )
}

export default ConnectWallet